﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace CKS.EBE.API
{
    internal class Themes
    {
        public static List<string> GetThemes(SPWeb oWeb)
        {
            var themes = new List<string>();

            try
            {
                SPFolder oThemesFolder = GetThemesFolder(oWeb);

                foreach (SPFolder oFolder in oThemesFolder.SubFolders)
                {
                    var masterFile = oWeb.GetFile(string.Format("themes/{0}/theme.master", oFolder.Name));
                    if (oFolder.Name != "Forms" && oFolder.Name != "Blank" && masterFile.Exists)
                    {
                        themes.Add(oFolder.Name);
                    }
                }

                // order themes by name
                themes.Sort();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            return themes;
        }

        public static SPFolder GetThemesFolder(SPWeb oWeb)
        {
            SPFolder oThemesFolder = null;
            try
            {
                if (BlogContext.Current.Settings.UseSiteCollectionThemes)
                {
                    if (oWeb.IsRootWeb)
                    {
                        // if the web is the rootweb, use it
                        oThemesFolder = oWeb.GetFolder("Themes");
                    }
                    else
                    {
                        // if the web is not the rootweb, get the rootweb
                        using (var site = new SPSite(oWeb.Url))
                        using (var rootWeb = site.RootWeb)
                        {
                            oThemesFolder = rootWeb.GetFolder("Themes");
                        }
                    }
                }
                else
                {
                    oThemesFolder = oWeb.GetFolder("Themes");
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
            
            return oThemesFolder;
        }
    }
}
